package com.mf.controller.threadPool;

import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lmf
 * @Create: 2025/5/28 22:02
 * @module 定时任务的线程池
 * @Description: 而这个线程池就是可以以一定周期去执行一个任务，或者是延迟多久执行一个任务一次
 */
@RestController
@RequestMapping("/newScheduleThreadPool")
public class newScheduleThreadPool {
    ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);

    @RequestMapping("/test")
    @Operation(summary = "正常执行")
    public void test() {
        pool.execute(() -> {
            System.out.println(Thread.currentThread().getName() + "：1");
        });
    }

    @RequestMapping("/test2")
    @Operation(summary = " 延迟执行，执行当前任务延迟5s后再执行")
    public void test2() {
        System.out.println(System.currentTimeMillis());
        pool.schedule(() -> {
            System.out.println(Thread.currentThread().getName() + System.currentTimeMillis() + "：2");
        }, 5, TimeUnit.SECONDS);
    }

    @RequestMapping("/test3")
    @Operation(summary = " 周期任务，第一次延迟5秒执行，然后每3秒执行异常任务 （下次执行时间时，是从任务刚刚开始时就计算）")
    public void test3() {
        System.out.println(System.currentTimeMillis());
        pool.scheduleAtFixedRate(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + System.currentTimeMillis() + "：3");
        }, 5, 3, TimeUnit.SECONDS);
    }

    @RequestMapping("/test4")
    @Operation(summary = " 周期任务，第一次延迟5秒执行，然后每3秒执行异常任务（下次执行时间时，会等待任务结束后，再计算时间）")
    public void test4() {
        System.out.println(System.currentTimeMillis());
        pool.scheduleWithFixedDelay(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + System.currentTimeMillis() + "：3");
        }, 5, 3, TimeUnit.SECONDS);
    }


}
